const app = getApp()
import { getMaterialBookGenerateInfo, saveFile, saveIslandMaterialBook, saveMaterialBook, getIslandMaterialBookGenerateInfo } from '../../../../api/index'
const uploadOss = require('../../../../utils/upload/uploadImg.js')
import { uuid } from '../../../../utils/util'

Page({
  data: {
    projectId: '',
    ids: '',
    safeBottom: 0,
    activeMaterial: '',
    currentMaterial: {
      fileManage: {
        fileUrl: ''
      },
      coverFileManage: {}
    },
    dynamicLabel: '',
    dynamicValue: '',
    explainLabel: '',
    explainValue: '',
    form: {
      diyList: []
    },
    fileManage: [],
    coverFileManage: [],
    coverimage: [],
    showMaterialPop: false
  },
  addMaterial () {
    this.setData({ showMaterialPop: true })
  },
  closeMaterial () {
    this.setData({ showMaterialPop: false })
  },
  confirmMaterial ({ detail }) {
    this.data.form.diyList.push(detail)
    this.setData({ 'form.diyList': this.data.form.diyList, showMaterialPop: false })
  },
  selectMaterial ({ currentTarget: { dataset: { item } } }) {
    this.setData({ activeMaterial: item.materialId, currentMaterial: item })
  },
  deleteMaterial () {
    let index = this.data.form.materialList.findIndex(item => item.projectMaterialId === this.data.currentMaterial.projectMaterialId)
    if (index > -1) {
      this.data.form.materialList.splice(index, 1)
      if (this.data.form.materialList.length) {
        if (index === 0) {
          this.data.activeMaterial = this.data.form.materialList[0].materialId
          this.data.currentMaterial = this.data.form.materialList[0]
        }
      } else {
        this.data.currentMaterial = {}
      }
    }
    this.setData({
      'form.materialList': this.data.form.materialList,
      activeMaterial: this.data.activeMaterial,
      currentMaterial: this.data.currentMaterial
    })
  },
  async save () {
    try {
      let query = { ...this.data.form }
      if (!query.bookName) {
        wx.showToast({ title: '请先输入材料册名称！', icon: 'none' })
        return
      }
      if (this.locking) return
      this.locking = true
      query.materialBookName = query.bookName
      query.projectId = this.data.projectId
      query.materialList.forEach(item => {
        if (!item.fileManage || !item.fileManage.fileUrl) item.fileManage = {}
        if (item.coverFileManage && item.coverFileManage.fileUrl) {
          item.materialCoverUrl = item.coverFileManage.url
        }
      })
      
      if (this.data.type === 'islandProject') {
        query.projectCity = this.data.city
        query.roleIds = this.data.roleIds.split(',')
        query.businessType = this.data.businessType
        await saveIslandMaterialBook({ ...query })
      } else {
        await saveMaterialBook({ ... query })
      }
      wx.showToast({ title: '材料册生成成功！', icon:'none' })
      setTimeout(() => {
        wx.$nav.navigateBack()
      }, 1500)
      this.locking = false
      // wx.$nav.navigateBack()
    } catch (err) {
      this.locking = false
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  setCurrentMaterial () {
    let index = this.data.form.materialList.findIndex(item => item.materialId === this.data.currentMaterial.materialId)
    if (index > -1) {
      let key = `form.materialList[${index}]`
      this.setData({ [key]: this.data.currentMaterial })
    }
  },
  deleteItem ({ currentTarget: { dataset: { key, index } } }) {
    this.data.currentMaterial[key].splice(index, 1)
    this.setData({ ['currentMaterial.' + key]: this.data.currentMaterial[key] })
    this.setCurrentMaterial()
  },
  changeArrayInput ({ currentTarget: { dataset: { key, index } }, detail }) {
    let setKey = `currentMaterial.${key}[${index}].paramValue`
    this.setData({ [setKey]: detail.value })
    this.setCurrentMaterial()
  },
  changeInput ({ currentTarget: { dataset: { key } }, detail }) {
    this.setData({ [key]: detail.value })
  },
  changeCurrentInput ({ currentTarget: { dataset: { key } }, detail }) {
    this.setData({ ['currentMaterial.' + key]: detail.value })
    this.setCurrentMaterial()
  },
  changeFormInput ({ currentTarget: { dataset: { key } }, detail }) {
    this.setData({ ['form.' + key]: detail.value })
  },
  addDynamicArray () {
    if (!this.data.dynamicLabel) {
      wx.showToast({ title: '请输入要添加的属性名称！', icon: 'none' })
      return
    }
    this.data.currentMaterial.dynamicArray.push({ paramName: this.data.dynamicLabel, paramValue: this.data.dynamicValue })
    this.setData({ 'currentMaterial.dynamicArray': this.data.currentMaterial.dynamicArray, dynamicLabel: '', dynamicValue: '' })
    this.setCurrentMaterial()
  },
  addExplainArray () {
    if (!this.data.explainLabel) {
      wx.showToast({ title: '请输入要添加的属性名称！', icon: 'none' })
      return
    }
    this.data.currentMaterial.explainArray.push({ paramName: this.data.explainLabel, paramValue: this.data.explainValue })
    this.setData({ 'currentMaterial.explainArray': this.data.currentMaterial.explainArray, explainValue: '', explainValue: '' })
    this.setCurrentMaterial()
  },
  deleteFile ({ currentTarget: { dataset: { index, key } } }) {
    this.data.currentMaterial[`${key}`] = {}
    this.setData({
      ['currentMaterial.' + key]: this.data.currentMaterial[key]
    })
    this.setCurrentMaterial()
  },
  deleteTempFile ({ currentTarget: { dataset: { index, key } } }) {
    this.data[`${key}`].splice(index, 1)
    this.setData({
      [`${key}`]: this.data[key]
    })
    this.setCurrentMaterial()
  },
  async againUpload ({ target: { dataset: { key, item, index } } }) {
    let _this = this
    let tempFiles = this.data[key]
    tempFiles[index].success = ''
    _this.setData({
      fileList: tempFiles
    })
    const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
    if (file) {
      const { ResultSet } = await saveFile({
        fileList: [{
          fileSize: item.size,
          fileName: file.fileName,
          fileUrl: file.fileUrl
        }]
      })
      tempFiles.splice(index, 1)
      _this.data.currentMaterial[key] = {
        uuid: item.uuid,
        fileId: ResultSet.userData.fileIdList[0].fileId,
        fileName: file.fileName,
        fileUrl: ResultSet.userData.fileIdList[0].url,
        url: ResultSet.userData.fileIdList[0].fileUrl
      }
    } else {
      tempFiles[index].success = 1
      _this.setData({
        fileList: tempFiles
      })
    }
    _this.setData({
      [key]: tempFiles,
      ['currentMaterial.' + key]:  _this.data.currentMaterial[key]
    })
    if (key === 'coverFileManage') {
      _this.setData({ 'currentDiyItem.materialCoverUrl': _this.data.currentDiyItem.coverFileManage.fileUrl, 'currentDiyItem.coverFileId': _this.data.currentDiyItem.coverFileManage.fileId })
    }
    this.setCurrentMaterial()
  },
  addFile ({ target: { dataset: { key, num } } }) {
    let _this = this
    wx.chooseMedia({
      count: parseInt(num),
      mediaType: ['image'],
      async success (res) {
        _this.setData({ [`currentMaterial.${key}`]: {} })
        res.tempFiles.forEach(item => {
          item.uuid = uuid()
          item.progress = 0
        })
        _this.data[`${key}`].push(...res.tempFiles)
        _this.setData({
          [`${key}`]: _this.data[`${key}`]
        })
        let tempFiles = _this.data[`${key}`]
        let temFileList = []
        if (tempFiles.length) {
          temFileList = await Promise.all(tempFiles.map(async (item, index) => {
            const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
            if (file) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileSize: item.size,
                  fileName: file.fileName,
                  fileUrl: file.fileUrl
                }]
              })
              return {
                uuid: item.uuid,
                fileId: ResultSet.userData.fileIdList[0].fileId,
                fileName: file.fileName,
                fileUrl: ResultSet.userData.fileIdList[0].url,
                url: ResultSet.userData.fileIdList[0].fileUrl
              }
            } else {
              tempFiles[index].success = 1
              _this.setData({
                [`${key}`]: tempFiles
              })
            }
          }))
        }
        let tempFileList = temFileList.filter(item => item)
        _this.data.currentMaterial[key] = tempFileList[0]
        if (_this.data.currentMaterial[key] && _this.data.currentMaterial[key].uuid) {
          let rowIndex = tempFiles.findIndex(row => _this.data.currentMaterial[key].uuid === row.uuid)
          if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
        }
        _this.setData({
          [`${key}`]: tempFiles,
          [`currentMaterial.${key}`]: _this.data.currentMaterial[key]
        })
        if (key === 'coverFileManage') {
          _this.setData({ 'currentDiyItem.materialCoverUrl': _this.data.currentDiyItem.coverFileManage.fileUrl, 'currentDiyItem.coverFileId': _this.data.currentDiyItem.coverFileManage.fileId })
        }
        this.setCurrentMaterial()
      }
    })
  },
  changeCover () {
    let _this = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      async success (res) {
        uploadOss(res.tempFiles[0].tempFilePath, async (file) => {
          const { ResultSet } = await saveFile({
            fileList: [{
              fileSize: res.tempFiles[0].size,
              fileName: file.fileName,
              fileUrl: file.fileUrl
            }]
          })
          _this.setData({ 'form.coverUrl': ResultSet.userData.fileIdList[0].fileUrl, 'form.projectCoverUrl': ResultSet.userData.fileIdList[0].url })
        }, (err) => {
          console.log(err)
        })
      }
    })
  },
  uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (res) => {
          resolve(res)
        },
        (err) => {
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
  async getDetail () {
    try {
      const { ResultSet } = await getMaterialBookGenerateInfo({ projectId: parseInt(this.data.projectId), ids: this.data.ids })
      if (ResultSet.userData.materialList && ResultSet.userData.materialList.length) {
        ResultSet.userData.materialList.forEach(item => {
          item.coverFileManage = {
            url: item.img
          }
        })
        this.data.activeMaterial = ResultSet.userData.materialList[0].materialId
        this.data.currentMaterial = ResultSet.userData.materialList[0]
      }
      this.setData({ form: { ...ResultSet.userData, diyList: [] }, activeMaterial: this.data.activeMaterial, currentMaterial: this.data.currentMaterial })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getIslandDetail () {
    try {
      const { ResultSet } = await getIslandMaterialBookGenerateInfo({ projectId: parseInt(this.data.projectId), ids: this.data.ids })
      if (ResultSet.userData.materialList && ResultSet.userData.materialList.length) {
        ResultSet.userData.materialList.forEach(item => {
          item.coverFileManage = {
            url: item.img
          }
        })
        this.data.activeMaterial = ResultSet.userData.materialList[0].materialId
        this.data.currentMaterial = ResultSet.userData.materialList[0]
      }
      this.setData({ form: { ...ResultSet.userData, diyList: [] }, activeMaterial: this.data.activeMaterial, currentMaterial: this.data.currentMaterial })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ ids, projectId, type, businessType, roleIds, city }) {
    const { screenHeight, safeArea: { bottom } } = wx.$pro.getSystemInfoSync()
    this.setData({ safeBottom: screenHeight - bottom, projectId, ids })
    if (type === 'islandProject') {
      this.setData({ type })
      if (businessType) this.setData({ businessType })
      if (roleIds) this.setData({ roleIds })
      if (city) this.setData({ city })
      this.getIslandDetail()
    } else {
      this.getDetail()
    }
  }
})